#!/bin/bash

if [[ $# -ne 2 ]]; then
    echo "The format is as follows:"
    echo "bash relion-3.1.2.sh buildpath installpath"
    echo ":param buildpath: 应用构建绝对路径"
    echo ":param installpath: 应用安装绝对路径"
    exit 1
fi

[[ ! "$1" =~ ^/.* ||  "$1" = "/" ]] &&  echo "请输入正确的构建路径" && exit 1
[[ ! "$2" =~ ^/.* ||  "$2" = "/" ]] &&  echo "请输入正确的安装路径" && exit 1
buildpath=$1
installpath=$2
[[ "$buildpath" =~ .*/$ ]] && buildpath=${buildpath%/*}
[[ "$installpath" =~ .*/$ ]] && installpath=${installpath%/*}

set -e
wget -t 0 -c -P $buildpath https://github.com/3dem/relion/archive/refs/tags/3.1.2.tar.gz
tar xf $buildpath/3.1.2.tar.gz -C $buildpath && rm -rf $buildpath/relion-3.1.2.tar.gz
cp dependency/src/avx2neon.h /usr/include
cd $buildpath/relion-3.1.2

sed -i "39c #include <avx2neon.h>" src/jaz/lbfgs/arithmetic_sse_double.h
sed -i "39c #include <avx2neon.h>" src/jaz/lbfgs/arithmetic_sse_float.h

mkdir build
cd build
CC=clang CXX=clang++ cmake -DALTCPU=ON -DGUI=OFF CPPFLAGS="$installpath/fftw-3.3.10/include" -DCMAKE_INSTALL_PREFIX=$installpath/relion-3.1.2  ..
make 
make install

rm -rf $buildpath/relion-3.1.2

cat>"$installpath/relion-3.1.2/relion_modulefiles"<<EOF
#%Module1.0
conflict relion
variable modfile [file normalize [info script]]
proc getModulefileDir {} {
    variable modfile
    set modfile_path [file dirname \$modfile]
    return \$modfile_path
}
set pwd [getModulefileDir]
set RELION \$pwd
setenv RELION \$RELION
prepend-path PATH \$RELION/bin
EOF

